# 迭代对象
# str list tuple dict set 等
# 对象实现了 __iter__()
# __iter__() 返回了迭代器对象

# isinstance() 判断对象是否是可迭代对象
from collections.abc import Iterable

print(isinstance('1234', (int, str)))
for i in 'abc':
    print(i)
# iter() 获取可迭代对象的迭代器
# next() 获取元素
li = ['a', 'b', 'c', 'd']
# 迭代器
# li2 = iter(li)
li2 = li.__iter__()
print(li2)
print(next(li2))
print(next(li2))
print(next(li2))
print(next(li2))
print(dir(li))
# 引发 StopIteration 异常
# print(next(li2))
from collections.abc import Iterable, Iterator

name = 'zhangsan'
print(isinstance(name, Iterable))
print(isinstance(name, Iterator))
name = iter(name)  # 将name转为迭代器对象
print(isinstance(name, Iterable))
print(isinstance(name, Iterator))


# 一个对象拥有 __iter__() 是可迭代对象
# 一个对象拥有 __iter__() 和 __next__() 是迭代器对象

# 自定义迭代器类
# __iter__() __next__()
class MIterator(object):
    def __init__(self):
        self.num = 0

    def __iter__(self):
        return self

    def __next__(self):
        if self.num >= 10:
            raise StopIteration("终止迭代")
        self.num += 1
        return self.num


mi = MIterator()

for i in mi:
    print(i)

# 生成器 generator
# 列表推导式
li = [i * 5 for i in range(5)]
print(li)
# 生成器
gen = (i * 5 for i in range(5))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))


# 使用了yied关键字的函数称之为生成器函数
def gen():
    print("开始了")
    yield 'a'
    yield 'b'
    yield 'c'


gen_01 = gen()
print(gen_01)
print(next(gen_01))
print(next(gen_01))
print(next(gen_01))


# 抛出 StopIteration 异常
# print(next(gen_01))
def gen2(n):
    a = 0
    while a < n:
        yield a
        a += 1


for i in gen2(10):
    print(i)
